package com.luochen.cdpt.util;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * @Auther: star
 * @Date: 2018/12/16 12:06
 * @Description:
 */
public class SqlUtil {

    public static  String bulidSql(String tableNmae, Map<String,String> map){
        String sql = "from "+tableNmae+" where 1=1";
        return getString(map, sql);
    }

    public static String bulidSql(Map<String,String> map){
        String sql = "";
        return getString(map, sql);

    }

    private static String getString(Map<String, String> map, String sql) {
        Set<String> keySet = map.keySet();
        for(String key : keySet){
            if(!StringUtils.isEmptry(map.get(key))){
                sql = sql + " and "+ key +"="+"'"+map.get(key)+"'";
            }
        }
        return sql;
    }

    public static void setPageParam(HttpServletRequest request, Query query){
        if (!StringUtils.isEmptry(request.getParameter("page"))
                && !StringUtils.isEmptry(request.getParameter("size"))) {
            int page = Integer.parseInt(request.getParameter("page"));
            int size = Integer.parseInt(request.getParameter("size"));
            query.setFirstResult((page - 1) * size);
            query.setMaxResults(size);
        }
    }

    public static String getOrderSql(String sql,String column){
        return sql = sql + " oder by "+column + " DESC";
    }
}
